package attribute;

import java.lang.reflect.Field;

class Animal{
    protected int weight;
}

class Person extends Animal {
    public int height;
    private String name;
    private String gender;
    private String birthday;

    private Person() {
    }

    public Person(String name){
        this.name = name;
    }

    public Person(String name, String gender, String birthday) {
        this.name = name;
        this.gender = gender;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    private void secrete(String content) {
        System.out.println("Show secrete is : " + content);
    }

    protected void sayHello(String msg) {
        System.out.println("hello," + msg);
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", birthday='" + birthday + '\'' +
                '}';
    }

}

public class ReflectAttributesDemo {
    public static void main(String[] args) throws Exception {
        Class clazz = Class.forName("attribute.Person");

        Field[] fields =  clazz.getFields();
        System.out.println("------the result for getFields--------");
        for(Field field : fields){
            System.out.println(field.toGenericString());
        }

        fields =  clazz.getDeclaredFields();
        System.out.println("------the result for getDeclaredFields--------");
        for(Field field : fields){
            System.out.println(field.toGenericString());
        }

        Field field = clazz.getField("height");
        System.out.println("------the result for getField--------");
        System.out.println(field.toGenericString());

        //field = clazz.getField("name"); //错误，不能访问私有属性
        //System.out.println(field.toGenericString());

        field = clazz.getDeclaredField("name");
        System.out.println("------the result for getDeclaredField--------");
        System.out.println(field.toGenericString());
        Person p = new Person("张三");
        field.setAccessible(true); //获取私有属性值前必须设置可访问
        System.out.println(field.get(p));

    }
}
